<template>
  <px-dialog v-model="visible" draggable title="上传文件" @close="cancel">
    <div>
      <px-upload
        ref="upload"
        v-model:file-list="fileList"
        class="upload-demo"
        :limit="limit"
        drag
        action="#"
        :auto-upload="false"
        :on-change="onChange"
        :on-exceed="handleExceed"
      >
        <px-icon class="px-icon--upload"><upload-filled /></px-icon>
        <div class="el-upload__text">拖拽到这里或<em>点击上传</em></div>
        <template #tip>
          <div class="px-upload__tip">文件需小于1G</div>
        </template>
      </px-upload>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancel">取消</px-button>
        <px-button type="primary" @click="confirmUpload">确定</px-button>
      </span>
    </template>
  </px-dialog>
</template>

<script setup>
import { computed, ref } from "vue";
import { UploadFilled } from "@px-ui/icons-vue";
import { PxMessage, genFileId } from "px-ui";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  limit: {
    type: Number,
    default: 1
  },
  folderData: {
    type: Object,
    default: () => {}
  },
  actionUrl: {
    type: String,
    default: ""
  }
});
const emits = defineEmits(["update:visible", "uploadAction"]);

const visible = computed({
  get: () => props.visible,
  set: val => emits("update:visible", val)
});

const fileList = ref([]);

const ACCEPTED_EXTENSIONS = ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "pdf"];
const upload = ref();
const handleExceed = files => {
  upload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value.handleStart(file);
};

/**
 * 文件选择改变时触发
 */
function onChange(file, fileListVal) {
  // const extension = file.name.split(".").pop().toLowerCase();
  // if (!ACCEPTED_EXTENSIONS.includes(extension)) {
  //   PxMessage.error("仅支持 doc, docx, xls, xlsx, ppt, pptx, txt, pdf格式的文件");
  //   fileList.value.pop();
  //   return;
  // }
  const fileSizeLimit = file.size / 1024 / 1024 / 1024 < 1;
  if (!fileSizeLimit) {
    PxMessage.error("文件大小需小于1G");
    fileList.value.pop();
    return;
  }
  fileList.value = fileListVal;
}

/**
 * 提交请求
 * 处理上传逻辑
 */
const confirmUpload = async () => {
  if (fileList.value.length === 0) {
    return PxMessage.error("请选择要上传的文件");
  }
  emits("uploadAction", fileList.value);
};

const cancel = () => {
  fileList.value = [];
  emits("update:visible", false);
};

defineExpose({
  cancel
});
</script>

<style lang="scss" scoped>
p {
  line-height: 36px;

  .label {
    display: inline-block;
    width: 80px;
    color: #000;
    text-align: right;
  }
}
</style>
